#include "QMsgTextEdit.h"
#include <QMovie>

QMsgTextEdit::QMsgTextEdit(QWidget *parent)
	: QTextEdit(parent)
{
	//setFontPointSize(10);

	
}

QMsgTextEdit::~QMsgTextEdit()
{
	delentAllEmotionImage();
	
}

void QMsgTextEdit::addEmotionUrl(int emotionNum)
{
	const QString &emotionPath =
		QString(":/Resources/MainWindow/emotion/%1.png").arg(emotionNum);

	insertHtml(QString("<img src='qrc%1' />").arg(emotionPath));

	if(m_listEmotionUrl.contains(emotionPath)) {
		return;
	}
	else 
	{
		m_listEmotionUrl.append(emotionPath);
	}

	QMovie *emotionMovie = new QMovie(emotionPath, "apng", this);
	connect(
		emotionMovie, SIGNAL(frameChanged(int)),
		this, SLOT(onEmotionImageFrameChange)
	);

	emotionMovie->start();

	updateGeometry();
}

void QMsgTextEdit::delentAllEmotionImage()
{
	qDeleteAll(m_emotionMap.keyBegin(), m_emotionMap.keyEnd());
	m_emotionMap.clear();
}

void QMsgTextEdit::onEmotionImageFrameChange(int frame)
{
	QMovie *movie = qobject_cast<QMovie*>(sender());

	movie->fileName();

	document()->addResource(
		QTextDocument::ResourceType::ImageResource,
		QUrl(movie->fileName()),
		movie->currentImage()
	);
}
